import React, { useEffect, useState } from 'react';
import { Form } from 'antd';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import { institutionChildren } from '@/pages/WorkFlow/components/FormControls/formConfig/custom/institution';
import moment from 'moment';
import customValidator from '@/pages/WorkFlow/components/FormControls/components/validator';
import { FormContainer } from '@/components/UserForm';
import cn from 'classnames';
import styles from '@/pages/Flow/Mine/MyApplication/Detail.less';

const { Item } = Form;

const Institution = ({ form, dataSource, wrapperLayout, formValueMap }) => {
    const { firstOrgInfo } = JSON.parse(localStorage.getItem('user') ?? {});
    const [institutionType, setInstitutionType] = useState();
    const [list, setList] = useState(institutionChildren);
    const { firstCompanyCode, firstCompanyName } = firstOrgInfo;

    const { getFieldDecorator } = form;

    const init = {
        scope: { key: firstCompanyCode, label: firstCompanyName },
        applyDate: moment().format('YYYY-MM-DD'),
        institutionType,
        releaseType: {
            releaseTypeName: '新规章制度发布',
            releaseType: 'new',
            originInstitutionName: undefined,
            originInstitutionId: undefined
        },
        effectiveDate: {
            auditEffectFlagName: '审核通过即可生效',
            auditEffectFlag: 'yes',
            startTime: undefined,
            endTime: undefined
        }
    };

    const handleOnInstitutionTypeChange = changeValue => {
        form.setFieldsValue({ institutionType: changeValue });
        setInstitutionType(changeValue);
    };

    // 根据文件名返回格式，比如a.pdf 返回pdf
    const getFileType = fName => fName.split('.')[1].toLowerCase();
    const renderIframe = file => {
        if (file.length > 0) {
            // 将s3替换成oss
            const docUrl = encodeURIComponent(file[0].url);
            const url = `https://view.officeapps.live.com/op/view.aspx?src=${docUrl}`;

            return file[0].url ? (
                <FormContainer>
                    <Item label="制度文件" vvspan={24} required>
                        <b style={{ color: '#000' }}>{file[0].originName}</b>
                        <div style={{ fontWeight: 'bold' }}>{file[0].name}</div>
                        <div className={cn(styles.textWrap, styles[getFileType(file[0].name)])}>
                            <div className={styles.maskTop}>
                                <i className={styles.logo} />
                                微微科技内部文件，仅供查看
                            </div>
                            <div className={styles.maskBottom} />
                            <iframe
                                title="制度文件"
                                style={{
                                    width: '100%',
                                    height: '600px',
                                    border: 0
                                }}
                                src={url}
                            ></iframe>
                        </div>
                    </Item>
                </FormContainer>
            ) : (
                ''
            );
        }
        return '';
    };

    useEffect(() => {
        if (dataSource?.children?.length > 0) {
            setList(dataSource?.children);
        }
    }, [dataSource]);

    return (
        <>
            {list &&
                list.map(v => {
                    const { tag, initialValue, formId, label, options } = v;
                    let layout = null;
                    if (tag === 'OssUpload') {
                        layout = wrapperLayout;
                    } else {
                        layout = {
                            labelCol: { span: 4 },
                            wrapperCol: { span: 8 }
                        };
                    }
                    let renderTag;
                    const rules =
                        v?.rules?.length > 0 && v?.rules[0]?.required && v.customValidatorRule
                            ? [{ ...v.rules[0], validator: customValidator[v.customValidatorRule] }]
                            : v.rules;

                    let initValue = initialValue || init[formId] || (formValueMap && formValueMap[formId]);

                    if (tag === 'Title') {
                        renderTag = <AutoRenderComponent config={v} key={formId} />;
                    } else if (tag === 'OssUpload' && initValue) {
                        renderTag = renderIframe(initValue);
                    } else {
                        if (tag === 'InstitutionType') {
                            options.onChange = handleOnInstitutionTypeChange;
                        }

                        if (tag === 'ReleaseType') {
                            options.institutionType = institutionType;
                            options.companyCode = firstCompanyCode;
                        }

                        if (tag === 'CompanyTree') {
                            const arr = [];
                            if (initialValue) {
                                const keyarr = initialValue?.key?.split(',').filter(s => s && s.trim());
                                const labelarr = initialValue?.label?.split(',').filter(s => s && s.trim());
                                if (keyarr && keyarr.length > 0) {
                                    keyarr.forEach((item, index) => {
                                        arr.push({ label: labelarr[index], value: item });
                                    });
                                }
                            }
                            initValue = arr;
                        }

                        renderTag = (
                            <Item label={label} key={formId} {...layout}>
                                {getFieldDecorator(v.formId, {
                                    initialValue: initValue,
                                    rules
                                })(<AutoRenderComponent config={v} form={form} {...options} />)}
                            </Item>
                        );
                    }

                    return renderTag;
                })}
        </>
    );
};

export default Institution;
